package com.second.system.controller;

import com.alibaba.fastjson.JSON;
import com.second.common.pojo.Permission;
import com.second.common.pojo.User;
import com.second.common.vo.Result;
import com.second.system.service.PermissionService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: second-education-parent
 * @description:
 * @author: 王子朋
 * @create: 2023-05-23 18:34
 **/
@RestController
@RequestMapping("system/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("leftMenu")
    @ApiOperation(value = "获取当前用户具有的左侧菜单")
    public Result leftMenu(HttpServletRequest request){
        //1.从请求头获取token信息
        String token = request.getHeader("token");
        //2.从redis中获取当前登录者的信息
        String json = redisTemplate.opsForValue().get("user::" + token);
        User user = JSON.parseObject(json, User.class);
        List<Permission> permissions = permissionService.findByUserId(user.getId());
        return Result.success(permissions);
    }
    @PostMapping("/list/{roleId}")
    @ApiOperation(value = "查询所有权限以及角色所具有的权限")
    public Result list(@PathVariable String roleId){
        List<Permission> permissionList = permissionService.findAll();
        List<String> permissionIds =permissionService.findByRoleId(roleId);
        Map<String,Object> map = new HashMap<>();
        map.put("permissionList",permissionList);
        map.put("permission",permissionIds);
        return  Result.success(map);
    }
    @GetMapping("confirm")
    @ApiOperation("确认分配权限")
    public Result confirm(@RequestParam String roleId,@RequestParam String[] checkPermissionIds){
        permissionService.confirm(roleId,checkPermissionIds);
        return Result.success();
    }
}
